﻿/*
 * Created by Ranorex
 * User: yuanz
 * Date: 2018/7/22
 * Time: 16:10
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Threading;
using WinForms = System.Windows.Forms;

using Ranorex;
using Ranorex.Core;
using Ranorex.Core.Testing;

using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;

namespace BlankProj_AT.CommonFunction
{
	public class CommonFunc
	{
		/// <summary>
		/// Constructs a new instance.
		/// </summary>
		public CommonFunc()
		{
			// Do not delete - a parameterless constructor is required!
		}
		
		//控件库
		public static BlankProj_AT.BlankProj_ATRepository repo = BlankProj_AT.BlankProj_ATRepository.Instance;
		
		#region 获取App内存
		/// <summary>
		/// 时间：2018-3-16
		/// 作者：袁郑
		/// 功能：获取App内存
		/// </summary>
		/// <param name="AppName">应用名称</param>
		public static void CurAppMemory(string AppName)
		{
			//App内存
			long curMemory = 0;
			Process[] process = Process.GetProcessesByName(AppName);
			foreach(var item in process)
				curMemory += item.WorkingSet64 / (1024*1024);
			string memoryLogInfo = System.DateTime.Now.ToString("H:mm:ss") + " : " +curMemory;
			Report.Info(">>>>>Current" + AppName + "Memory = " + curMemory.ToString() + "M<<<<<");
			
			//创建内存日志
			Logmsg(memoryLogInfo, AppName, AppName);
			Delay.Milliseconds(500);
		}
		#endregion
		
		#region 获取系统内存使用情况
		/// <summary>
		/// 时间：2018-4-11
		/// 作者：袁郑
		/// 功能：获取系统内存使用情况
		/// </summary>
		public static PerformanceCounter cpu;
		public static void CurSysMemoryInfo()
		{
			cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
			// cif = new ComputerInfo();
			MEMORY_INFO MemInfo;
			MemInfo = new MEMORY_INFO();

			GlobalMemoryStatus(ref  MemInfo);
			Report.Info(">>>>>" + MemInfo.dwMemoryLoad.ToString() + "%的内存正在使用<<<<<");
			System.Threading.Thread.Sleep(2000);
		}
		[DllImport("kernel32")]
		public static extern void GetSystemDirectory(StringBuilder SysDir, int count);
		[DllImport("kernel32")]
		public static extern void GetSystemInfo(ref  CPU_INFO cpuinfo);
		[DllImport("kernel32")]
		public static extern void GlobalMemoryStatus(ref  MEMORY_INFO meminfo);
		[DllImport("kernel32")]
		public static extern void GetSystemTime(ref  SYSTEMTIME_INFO stinfo);
		
		//定义CPU的信息结构
		[StructLayout(LayoutKind.Sequential)]
		public struct CPU_INFO
		{
			public uint dwOemId;
			public uint dwPageSize;
			public uint lpMinimumApplicationAddress;
			public uint lpMaximumApplicationAddress;
			public uint dwActiveProcessorMask;
			public uint dwNumberOfProcessors;
			public uint dwProcessorType;
			public uint dwAllocationGranularity;
			public uint dwProcessorLevel;
			public uint dwProcessorRevision;
		}
		//定义内存的信息结构
		[StructLayout(LayoutKind.Sequential)]
		public struct MEMORY_INFO
		{
			public uint dwLength;
			public uint dwMemoryLoad;
			public uint dwTotalPhys;
			public uint dwAvailPhys;
			public uint dwTotalPageFile;
			public uint dwAvailPageFile;
			public uint dwTotalVirtual;
			public uint dwAvailVirtual;
		}
		//定义系统时间的信息结构
		[StructLayout(LayoutKind.Sequential)]
		public struct SYSTEMTIME_INFO
		{
			public ushort wYear;
			public ushort wMonth;
			public ushort wDayOfWeek;
			public ushort wDay;
			public ushort wHour;
			public ushort wMinute;
			public ushort wSecond;
			public ushort wMilliseconds;
		}

		#endregion
		
		#region 字符串中剔除不是数字的字符操作
		/// <summary>
		/// 功能：字符串中剔除不是数字的字符操作 2017/10/19 15:43:49 --> 20171019154349
		/// 作者：袁郑
		/// 时间：2017-12-6
		/// </summary>
		/// <param name="strItem">待处理的字符串</param>
		/// <returns>返回的字符串</returns>
		public static string  StrOperate4Date(string strItem)
		{
			StringBuilder sb = new StringBuilder();
			char[] charItem = strItem.ToCharArray();
			foreach(var item in charItem)
			{
				int ascNum = Asc(item.ToString());
				if(ascNum >= 48 && ascNum <= 57)
				{
					sb.Append(Chr(ascNum));
				}
			}
			return sb.ToString();
		}
		
		#region ASCII和字符串的转换
		/// <summary>
		/// 功能：字符转ASCII
		/// 作者：袁郑
		/// 时间：2017-12-6
		/// </summary>
		/// <param name="chrItem">字符</param>
		/// <returns>返回的字符串</returns>
		private static int Asc(string chrItem)
		{
			if(chrItem.Length == 1)
			{
				System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
				int intAsciiCode = (int)asciiEncoding.GetBytes(chrItem)[0];
				return (intAsciiCode);
			}
			else
			{
				throw new Exception("Character is not valid.");
			}
		}
		
		/// <summary>
		/// 功能：ASCII转字符串
		/// 作者：袁郑
		/// 时间；2017-12-6
		/// </summary>
		/// <param name="asciiCode">ASCII码</param>
		/// <returns>字符串</returns>
		private static string Chr(int asciiCode)
		{
			if (asciiCode >= 0 && asciiCode <= 255)
			{
				System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
				byte[] byteArray = new byte[] { (byte)asciiCode };
				string strCharacter = asciiEncoding.GetString(byteArray);
				return (strCharacter);
			}
			else
			{
				throw new Exception("ASCII Code is not valid.");
			}
		}
		#endregion
		#endregion
		
		#region 获取程序基目录
		/// <summary>
		/// 时间：2018-7-22
		/// 作者：袁郑
		/// 功能：获取项目基准目录 ---> [ProjName]\bin\Debug
		/// </summary>
		/// <returns>返回基准目录</returns>
		public static string ReturnBaseDirectory()
		{
			string str=System.AppDomain.CurrentDomain.BaseDirectory;
			str = str.Substring(0,str.LastIndexOf("\\"));
			str = str.Substring(0,str.LastIndexOf("\\"));
			str = str.Substring(0,str.LastIndexOf("\\"));
			Report.Info(str);
			return str;
		}
		#endregion
		
		#region 给字符串加上时间标记
		/// <summary>
		/// 时间：2018-4-2
		/// 作者：袁郑
		/// 功能：给字符串加上时间标记
		/// </summary>
		/// <param name="StrName">字符串</param>
		/// <returns>返回带有时间标记的字符串</returns>
		public static string GetStrTimeMark(string StrName)
		{
			System.DateTime dt = System.DateTime.Now; //获取当前时间
			string strCurDate = dt.ToString("yyyy-MM-dd HH:mm:ss");
			strCurDate = CommonFunc.StrOperate4Date(strCurDate);
			StrName += strCurDate;
			Report.Info("时间标记字符串=" + StrName);
			return StrName;
		}
		#endregion
		
		#region 创建日志
		/// <summary>
		/// 时间：2018-4-11
		/// 作者：袁郑
		/// 功能：创建日志
		/// </summary>
		/// <param name="LogInfo"></param>
		/// <param name="LogName"></param>
		public static void Logmsg(string LogInfo, string LogName, string LogType)
		{
			//log信息
			string log = "";
			log += LogInfo + "\r\n";
			
			//生成到debug目录下
			string basePath = ReturnBaseDirectory();
			string path = basePath + @"\bin\Debug\" + LogType;
			
			//生成目录
			//创建文件夹
			if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
			{
				Directory.CreateDirectory(path);
			}

			// 判断文件是否存在，不存在则创建，否则读取值显示到txt文档
			if (!System.IO.File.Exists(path + "/" + LogName + "log_" + System.DateTime.Today.ToString("yyyy-MM-dd") + ".txt"))
			{
				FileStream fs1 = new FileStream(path + "/" + LogName + "log_" + System.DateTime.Today.ToString("yyyy-MM-dd") + ".txt", FileMode.Create, FileAccess.Write);//创建写入文件
				StreamWriter sw = new StreamWriter(fs1);
				sw.WriteLine(log);//开始写入值
				sw.Close();
				fs1.Close();
			}
			else
			{
				FileStream fs = new FileStream(path + "/" + LogName + "log_" + System.DateTime.Today.ToString("yyyy-MM-dd") + ".txt" + "", FileMode.Append, FileAccess.Write);
				StreamWriter sr = new StreamWriter(fs);
				sr.WriteLine(log);//开始写入值
				sr.Close();
				fs.Close();
			}
			
		}
		#endregion

	}
}
